const { db } = require('../../db');
const { mongoose } = require('../../db');

class RestService {

    async addService(ctx, { data, session }) {
        // 如果是like表，则需要判断是否已经点赞过，如果已经点赞过，则删除点赞
        if (ctx.modelName === 'Like') {
            const like = await db.model(ctx.modelName).findOne({ ...data, deletedAt: null }, null, { session });
            if (like) {
                await db.model(ctx.modelName).deleteOne({ ...data, deletedAt: null }, { session });
                return { deletedCount: 1 };
            }
        }
        return await db.model(ctx.modelName).create([data], { session });
    }

    async delService(ctx, { data, force, session }) {
        let res;
        if (force) {
            res = await db.model(ctx.modelName).deleteOne(data, { session });
        } else {
            res = await db.model(ctx.modelName).updateOne(data, { deletedAt: new Date() }, { new: true, session });
        }
        return res;
    }

    async restoreService(ctx, { data, session }) {
        const res = await db.model(ctx.modelName).updateOne(data, { deletedAt: null }, { new: true, session });
        return res;
    }

    async updateService(ctx, { data, session }) {
        const { _id } = data;
        delete data._id;
        const res = await db.model(ctx.modelName).findOneAndUpdate({ _id, deletedAt: null }, data, { new: true, session });
        return res;
    }

    async getByIdService(ctx, { id, session }) {
        const res = await db.model(ctx.modelName).findById({ _id: id, deletedAt: null }, null, { session }).populate('username')
        return res;
    }

    async getByPageService(ctx, { offset, limit, session }) {
        const res = await db.model(ctx.modelName).aggregate([
            { $match: { deletedAt: null } }, // 匹配条件
            {
                $facet: {
                    metadata: [{ $count: "total" }], // 获取满足条件的总记录数
                    data: [
                        { $skip: offset },
                        { $limit: limit },
                        { $sort: { createdAt: -1 } }
                    ] // 获取分页数据
                }
            }
        ]).session(session)
        return {
            count: res[0].metadata[0].total,
            rows: res[0].data
        }
    }

    async getAllService(ctx, { setOpts = {}, session, query = {} }) {
        const res = await db.model(ctx.modelName).find({ ...query, deletedAt: null }, null, setOpts).session(session);
        return res;
    }

}


module.exports = new RestService();